import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pornhub_app/components/diolog/dialog.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/community/publish_tags.dart';
import 'package:pornhub_app/model/image_upload_resp_model.dart';
import 'package:pornhub_app/utils/logger.dart';

class PostPublishPageController extends GetxController {
  final contentText = ''.obs;
  final selectedType = Rxn<String>();
  final isAgreedToRules = false.obs;
  final RxList<File> images = <File>[].obs;
  final ImagePicker _picker = ImagePicker();
  final RxList<PublishTags> publishTagsList = <PublishTags>[].obs;
  final RxBool isLoading = false.obs;

  final TextEditingController textController = TextEditingController();

  final RxList<String> uploadedImageUrls = <String>[].obs;

  final RxList<String> selectedTypes = <String>[].obs;

  // 清除所有数据
  void clearAllData() {
    contentText.value = '';
    textController.clear();
    selectedType.value = null;
    isAgreedToRules.value = false;
    images.clear();
    uploadedImageUrls.clear();
    selectedTypes.clear();
    update();
  }

  // 切换标签选择状态
  void toggleType(String type) {
    if (selectedTypes.contains(type)) {
      selectedTypes.remove(type);
    } else {
      selectedTypes.add(type);
    }
  }

  // 检查标签是否被选中
  bool isTypeSelected(String type) {
    return selectedTypes.contains(type);
  }

  // 清除所有选中的标签
  void clearSelectedTypes() {
    selectedTypes.clear();
  }

  @override
  void onInit() {
    super.onInit();
    getPublishTags();
    // 监听文本变化
    textController.addListener(() {
      contentText.value = textController.text;
    });
  }

  @override
  void onClose() {
    textController.dispose();
    super.onClose();
  }

  // 获取发布标签
  void getPublishTags() {
    isLoading.value = true;
    Api.getPublishTags().then((response) {
      if (response.isNotEmpty) {
        publishTagsList.value = (response as List<dynamic>)
            .map((item) => PublishTags.fromJson(item as Map<String, dynamic>))
            .toList();
        update();
      }
    }).catchError((error) {
      showToast("获取标签失败: ${error.toString()}");
    }).whenComplete(() {
      isLoading.value = false;
    });
  }

  // 选择图片
  Future<void> pickImages() async {
    if (images.length >= 9) {
      showToast("最多只能选择9张图片");
      return;
    }

    final remainingSlots = 9 - images.length;
    try {
      List<XFile> selectedImages = await _picker.pickMultiImage();

      if (selectedImages.isEmpty) return;

      if (selectedImages.length > remainingSlots) {
        selectedImages = selectedImages.sublist(0, remainingSlots);
        showToast("已达到最大选择数量");
      }

      // 检查并添加图片
      for (var image in selectedImages) {
        final file = File(image.path);
        images.add(file);
      }
    } catch (e) {
      showToast("选择图片失败: ${e.toString()}");
    }
  }

  // 删除图片
  void removeImage(int index) {
    if (index >= 0 && index < images.length) {
      images.removeAt(index);
    }
  }

  void setType(String type) {
    selectedType.value = type;
  }

  // 切换同意规则状态
  void toggleAgreement() {
    isAgreedToRules.value = !isAgreedToRules.value;
  }

  // 上传图片到服务器
  Future<void> uploadImages() async {
    if (images.isEmpty) return;

    for (var i = 0; i < images.length; i++) {
      try {
        // 读取文件为字节数据
        Uint8List imageBytes = await images[i].readAsBytes();

        // 上传图片并获取响应
        ImageUploadRspModel? response =
            await httpInstance.uploadImage(imageBytes, (count, total) {
          // 上传进度回调
          logger.d("上传进度: $count/$total");
        });

        // 处理上传成功的响应
        if (response != null && response.fileName != null) {
          // 更新图片路径
          final uploadedImagePath = response.fileName!;
          // 这里可以存储上传成功的图片路径，用于后续发布帖子时使用
          uploadedImageUrls.add(uploadedImagePath);
        } else {
          throw Exception('Upload failed: No response or filename');
        }
      } catch (e) {
        showToast("图片上传失败: ${e.toString()}");
        // 处理失败的情况
        return;
      }
    }
  }

  // 获取选中标签ID
  String getSelectedTagId() {
    final selectedTag = publishTagsList.firstWhere(
      (tag) => tag.name == selectedType.value,
      orElse: () => PublishTags(id: '', name: ''),
    );
    return selectedTag.id;
  }

  // 获取多个选中标签的ID和名称
  List<Map<String, String>> getSelectedTagsInfo() {
    List<Map<String, String>> selectedTagsInfo = [];

    for (String tagName in selectedTypes) {
      final selectedTag = publishTagsList.firstWhere(
        (tag) => tag.name == tagName,
        orElse: () => PublishTags(id: '', name: ''),
      );

      if (selectedTag.id.isNotEmpty) {
        selectedTagsInfo.add({
          'id': selectedTag.id,
          'name': selectedTag.name,
        });
      }
    }

    return selectedTagsInfo;
  }

  // 发布内容
  Future<void> publishRelease() async {
    // 基础验证
    if (contentText.value.trim().isEmpty) {
      showToast("请输入内容");
      return;
    }

    if (getSelectedTagsInfo().isEmpty) {
      showToast("请选择发布类型");
      return;
    }

    if (!isAgreedToRules.value) {
      showToast("请同意发布规则");
      return;
    }

    if (images.isEmpty) {
      showToast("至少选择1张图片");
      return;
    }

    isLoading.value = true;
    try {
      // 上传图片
      await uploadImages();

      // 构建发布参数
      final params = buildPublishParams(
        cityName: await getCityName(), // 获取城市名称
        content: contentText.value.trim(),
        coteries: getSelectedTagsInfo(),
        dynamicImg: uploadedImageUrls,
        gold: 0,
      );

      // 发布内容
      final response = await Api.publishRelease(params);

      if (response) {
        showToast("发布成功");
        clearAllData(); // 清除所有数据
        Get.back(result: true);
      } else {
        showToast("发布失败");
      }
    } catch (e) {
      showToast("发布失败: ${e.toString()}");
    } finally {
      isLoading.value = false;
    }
  }

  // 获取城市名称
  Future<String> getCityName() async {
    return '';
  }

  // 构建发布参数
  Map<String, dynamic> buildPublishParams({
    required String cityName,
    required String content,
    List<Map<String, String>>? coteries,
    List<String>? dynamicImg,
    int gold = 0,
    Map<String, dynamic>? video,
  }) {
    return {
      'cityName': cityName,
      'content': content,
      'coteries': coteries ?? [],
      'dynamicImg': dynamicImg ?? [],
      'gold': gold,
      if (video != null) 'video': video,
    };
  }

  // 构建视频参数
  Map<String, dynamic> buildVideoParams({
    required String checkSum,
    required List<String> coverImg,
    required int height,
    required String id,
    required int playTime,
    required int size,
    required String videoUrl,
    required int width,
  }) {
    return {
      'checkSum': checkSum,
      'coverImg': coverImg,
      'height': height,
      'id': id,
      'playTime': playTime,
      'size': size,
      'videoUrl': videoUrl,
      'width': width,
    };
  }
}
